"""
API路由处理模块
处理所有API路由和业务逻辑
"""

import logging
from fastapi import APIRouter, HTTPException
from fastapi.responses import FileResponse
from sse_starlette.sse import EventSourceResponse

# 使用绝对导入，只在backend目录设置__init__.py
from backend.config.constants import Config, ExamConstants
from backend.models.schemas import (
    GenerateRequest, 
    StreamGenerateRequest, 
    ExportRequest,
    GenerateResponse,
    ConfigResponse,
    HealthResponse
)
from backend.services.ai_service import ai_service
from backend.services.word_service import word_export_service

logger = logging.getLogger(__name__)

# 创建路由器
router = APIRouter()


@router.get("/health", response_model=HealthResponse)
async def health_check():
    """健康检查接口"""
    return HealthResponse(
        status="healthy",
        service="AI试卷生成器后端",
        version="1.0.0",
        model=Config.DEFAULT_MODEL
    )


@router.get("/config", response_model=ConfigResponse)
async def get_config():
    """获取支持的配置选项"""
    return ConfigResponse(
        grades=ExamConstants.GRADES,
        difficulties=ExamConstants.DIFFICULTIES,
        subjects=ExamConstants.SUBJECTS,
        question_types=ExamConstants.QUESTION_TYPES,
        knowledge_points=ExamConstants.KNOWLEDGE_POINTS,
        max_questions=Config.MAX_QUESTIONS
    )


@router.post("/generate", response_model=GenerateResponse)
async def generate_questions(request: GenerateRequest):
    """生成试题"""
    try:
        logger.info(f"生成试题请求: {request.grade} - {request.difficulty} - {request.subject} - {request.question_type} - {'/'.join(request.knowledge_points)} - {request.num_questions}道")
        
        # 准备参数
        params = {
            "grade": request.grade,
            "difficulty": request.difficulty,
            "subject": request.subject,
            "knowledge_points": request.knowledge_points,
            "question_type": request.question_type,
            "num_questions": request.num_questions
        }
        
        # 调用AI服务生成
        result = ai_service.generate_questions(params)
        
        logger.info("试题生成成功")
        return GenerateResponse(data=result, status="success")
        
    except ValueError as e:
        logger.error(f"参数验证失败: {e}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"生成试题失败: {e}")
        raise HTTPException(status_code=500, detail=f"生成试题失败: {str(e)}")


@router.post("/generate/stream")
async def stream_generate_questions(request: StreamGenerateRequest):
    """流式生成试题"""
    
    async def generate_stream():
        try:
            logger.info(f"流式生成试题请求: {request.grade} - {request.difficulty} - {request.subject} - {request.question_type} - {'/'.join(request.knowledge_points)} - {request.num_questions}道")
            
            # 准备参数
            params = {
                "grade": request.grade,
                "difficulty": request.difficulty,
                "subject": request.subject,
                "knowledge_points": request.knowledge_points,
                "question_type": request.question_type,
                "num_questions": request.num_questions
            }
            
            # 调用AI服务流式生成
            async for data in ai_service.generate_questions_stream(params):
                yield f"data: {data}\n\n"
                
        except ValueError as e:
            logger.error(f"参数验证失败: {e}")
            error_data = f'{{"type": "error", "message": "{str(e)}"}}'
            yield f"data: {error_data}\n\n"
        except Exception as e:
            logger.error(f"流式生成试题失败: {e}")
            error_data = f'{{"type": "error", "message": "生成试题失败: {str(e)}"}}'
            yield f"data: {error_data}\n\n"
    
    return EventSourceResponse(generate_stream())


@router.post("/export_word")
async def export_word(request: ExportRequest):
    """导出Word文档"""
    try:
        logger.info(f"开始导出Word文档")
        
        # 调用Word导出服务
        filepath = word_export_service.export_to_word(
            data=request.data,
            filename=request.filename,
            include_answers=request.include_answers
        )
        
        logger.info(f"Word文档导出成功: {filepath}")
        
        # 确定文件名
        filename = request.filename or "exam.docx"
        if not filename.endswith('.docx'):
            filename += '.docx'
        
        return FileResponse(
            path=filepath,
            media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
            filename=filename
        )
        
    except ValueError as e:
        logger.error(f"数据验证失败: {e}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"导出Word文档失败: {e}")
        raise HTTPException(status_code=500, detail=f"导出失败: {str(e)}")